package top.ajun.mall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.product.dao.AttrGroupDao;
import top.ajun.mall.product.entity.AttrEntity;
import top.ajun.mall.product.entity.AttrGroupEntity;
import top.ajun.mall.product.service.AttrGroupService;
import top.ajun.mall.product.service.AttrService;
import top.ajun.mall.product.vo.AttrGroupWithAttrsVo;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
            new Query<AttrGroupEntity>().getPage(params),
            Wrappers.query()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<AttrGroupEntity> wrapper = Wrappers.lambdaQuery();
        if (!StrUtil.isEmpty(key)) {
            wrapper.and(obj -> obj.eq(AttrGroupEntity::getAttrGroupId, key).or().like(AttrGroupEntity::getAttrGroupName, key));
        }
        if (catelogId != 0) {
            wrapper.eq(AttrGroupEntity::getCatelogId, catelogId);
        }
        return new PageUtils(page(new Query<AttrGroupEntity>().getPage(params), wrapper));
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        // 查出当前分类下的所有属性分组
        List<AttrGroupEntity> attrGroupList = this.list(
            Wrappers.<AttrGroupEntity>lambdaQuery()
                .eq(AttrGroupEntity::getCatelogId, catelogId)
        );

        // 查出每个分组的所有属性
        return attrGroupList.stream().map(group -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(group, vo);
            List<AttrEntity> attrList = attrService.getRelatedAttr(vo.getAttrGroupId());
            vo.setAttrs(attrList);
            return vo;
        }).collect(Collectors.toList());
    }

}